﻿using ExcelAutomator.Configuration;
using ExcelAutomator.Validation;

namespace ExcelAutomator.Executors.Macro
{
	[Executor(ExecutorName, ExecutorType, ExecutorAction)]
	internal class MacroRunExecutor : Executor<MacroConfiguration>
	{
		public const string ExecutorName = "Macro Run Executor";
		public const string ExecutorType = "macro";
		public const string ExecutorAction = "run";

		public override ExecutionResult OnExecute(ExecutionContext context)
		{
			if (Configuration.ExecutionContext == ExecutionContextConfiguration.InputWorkbook)
			{
				context.Application.RunMacro(context.InputWorkbook.Name, Configuration.Name);
				return ExecutionResult.CreateSuccess(string.Format("Run macro '{0}!{1}'", context.InputWorkbook.Name, Configuration.Name), context);
			}
			if (Configuration.ExecutionContext == ExecutionContextConfiguration.TargetWorkbook)
			{
				context.Application.RunMacro(context.TargetWorkbook.Name, Configuration.Name);
				return ExecutionResult.CreateSuccess(string.Format("Run macro '{0}!{1}'", context.TargetWorkbook.Name, Configuration.Name), context);
			}
			return ExecutionResult.CreateFailure(string.Format("Couldn't run the macro '{0}'.", Configuration.Name), context);
		}

		public override void OnConfigure(string xmlConfig, out MacroConfiguration configuration)
		{
			configuration = ConfigurationBuilder.Build<MacroConfiguration>(xmlConfig, Constants.ExecutorExtensionsNamespace);
		}

		public override void OnValidate(ValidationEngine validationEngine, ExecutionContext context)
		{
			//TODO Validation needed? 
		}

		public override string Name
		{
			get { return ExecutorName; }
		}

		public override string Type
		{
			get { return ExecutorType; }
		}

		public override string ActionId
		{
			get { return ExecutorAction; }
		}
	}
}
